<?php

/**
 * 摇一摇
 */
class api_shake
{
    private $_mid;
    private $_G;
    private $_openid;
    private $_memberId;
    private $_app;
    private $_wxConf;

    //21编号
    function __construct(){
        global $_G;
        $this->_G = &$_G;
        $this->_mid = $_GET['mid'];
        $this->_wxConf = array(
            "appId" => "wx52b1c0d4c35f2531",
            "secret" => "22a045d1bc56e0ca28cc1a5e7b6a52df"
        );
//        $this->_openid = $this->_G[$this->_mid]['openid'];
//        $this->_memberId = $this->_G[$this->_mid]['memberid'];
        $clientkey = getcookie('HeaderKey_' . $this->_mid);
        //POst过来的用户信息
        $clientkey = $clientkey ? $clientkey : $_GET['HeaderKey'];
        //解密用户信息
        $Token = getcookie("Token");
        $app = getcookie("third_party_wxweb");
        $this->_app= $app;
        list($auType, $openid, $mid, $subscribe) = explode("\t", SING_auth($clientkey, 'DECODE', md5(getglobal('cookiepre', 'config/cookie') . $Token)));

        if($app=='app'){
            $_G[$this->_mid]['memberid']=$this->_memberId= $openid;
            DB::SetMainDB(DB_MAIN);
            if($this->_memberId){
                $rs = DB::fetch_first(" select openid from %t  where display=1 and id=%d", array("common_member", $this->_memberId));
                $_G[$this->_mid]['openid']=$this->_openid= $rs['openid'];
            }
        }else{
            $_G[$this->_mid]['openid']=$this->_openid= $openid;
            DB::SetMainDB(DB_MAIN);
            if($this->_openid){
                $rs = DB::fetch_first(" select id from %t  where display=1 and openid=%s", array("common_member", $this->_openid));
                $_G[$this->_mid]['memberid']=$this->_memberId= $rs['id'];
            }
        }
    }

//    public function initPre()
//    {
//        $starttime=1520006400;
//        $id = $this->_G['g_id'];
//        DB::SetMainDB(DB_ESHOP);
//        $rs=DB::fetch_all(" select *,count(*) as count from %t  where pay_status=1 and tablename=%s and pay_time>=%d and member_id=%d ",array("es_order",'es_pre_sale',$starttime,$id));
//
//        foreach ($rs as $r) {
////            $g=R::REDID()->GET('shakeSendNum-'.$r['member_id']);
////            if($g){
////                R::REDID()->INCR('shakeSendNum-'.$r['member_id']);
////            }else{
////                R::REDID()->SET('shakeSendNum-'.$r['member_id'],1);
////            }
//            $g = redis2("set","shakeSendNum-".$r['member_id'],$r['count']);
//        }
//        return array("Error" => 0, "data" => $rs,"num" => $g);
//    }
//    public function initPer()
//    {
//        $starttime=1520006400;
//        DB::SetMainDB(DB_ESHOP);
//        $rs=DB::fetch_all(" select * from %t  where pay_status=1 and tablename=%s and pay_time>=%d ",array("es_order",'es_pre_sale',$starttime));
//
//        foreach ($rs as $r) {
////            $g=R::REDID()->GET('shakeSendNum-'.$r['member_id']);
////            if($g){
////                R::REDID()->INCR('shakeSendNum-'.$r['member_id']);
////            }else{
////                R::REDID()->SET('shakeSendNum-'.$r['member_id'],1);
////            }
//            $g= redis2("inc","shakeSendNum-".$r['member_id']);
//        }
//        return array("Error" => 0, "data" => $rs,"num" => $g);
//    }
//    public function initPer2()
//    {
//        $starttime=1520038800;
//        DB::SetMainDB(DB_ESHOP);
//        $rs=DB::fetch_all(" select * from %t  where pay_status=1 and tablename=%s and pay_time>%d ",array("es_order",'es_pre_sale',$starttime));
//
//        foreach ($rs as $r) {
////            $g=R::REDID()->GET('shakeSendNum-'.$r['member_id']);
////            if($g){
////                R::REDID()->INCR('shakeSendNum-'.$r['member_id']);
////            }else{
////                R::REDID()->SET('shakeSendNum-'.$r['member_id'],1);
////            }
//            $g= redis2("inc","shakeSendNum-".$r['member_id']);
//        }
//        return array("Error" => 0, "data" => $rs,"num" => $g);
//    }
//    public function initPer3()
//    {
//        $starttime=1520049600;
//        DB::SetMainDB(DB_ESHOP);
//        $rs=DB::fetch_all(" select * from %t  where pay_status=1 and tablename=%s and pay_time>%d",array("es_order",'es_pre_sale',$starttime));
//
//        foreach ($rs as $r) {
////            $g=R::REDID()->GET('shakeSendNum-'.$r['member_id']);
////            if($g){
////                R::REDID()->INCR('shakeSendNum-'.$r['member_id']);
////            }else{
////                R::REDID()->SET('shakeSendNum-'.$r['member_id'],1);
////            }
//            $g= redis2("inc","shakeSendNum-".$r['member_id']);
//        }
//        return array("Error" => 0, "data" => $rs,"num" => $g);
//    }
//    public function initTest()
//    {
//
//        DB::SetMainDB(DB_ESHOP);
//        $rs=DB::fetch_all("select id,member_id from %t where coupon_id=%d",array("es_coupon_log",4729));
//        foreach ($rs as $r) {
//            $g= redis2("set","queenpricecount-".$r['member_id'],$r['id']);
//        }
//        return array("Error" => 0, "data" => $rs,"num" => $g);
//    }
    public function code2login(){ //现在在中的
        $code = trim(strip_tags($this->_G['g_code']));
        $appId = "wx951684d2fdf00899";//'wx52b1c0d4c35f2531';//
        $secret = "7b8a3022909ff0a8e0791251ba60aa02";//'22a045d1bc56e0ca28cc1a5e7b6a52df';//
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appId.'&secret='.$secret.'&code=' . $code . '&grant_type=authorization_code';
//         $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appId.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';
        $data = DoCurl($url);
        $data = json_decode($data, true);
        if (array_key_exists("errcode", $data)) {
            return array("Error" => 1, "Msg" => "授权登录维护中，请使用其他方式登录", "errcode" => $data['errcode']);
        }
        return array("Error" => 0, "Msg" => "微信登录成功", "data"=>$data);
    }
    public function TestG()
    {
        $id = $this->_G['g_id'];
        $queen = redis2("get","queenpricecount-".$id);
        if($queen){
            return array("Error" => 0, "data" =>$queen);
        }else{
            return array("Error" => 1, "data" =>$queen);
        }

    }
    public function getPre()
    {
        $id = $this->_G['g_id'];
        $g=redis2("get","shakeSendNum-".$id);
        return array("Error" => 0, "num" => $g);
    }

    public function queryAllLog(){
        $thisData = redis2("get","allLogData77");
        return array("Error"=>0,"Msg"=>"数据获取成功","data"=>$thisData);
    }

    public function test()
    {
        $thisData = redis2("zrange","allLogData66",array(-10,-1));
        return array("Error"=>0,"Msg"=>"数据获取成功","data"=>$thisData);
    }

    public function queryCache(){
//        $befData = redis2("get","shakeSendNum-2073243");
//        $shakeuserdata = redis2("get","shakeUser-2073243-46");
//        ddkddkdkdk

        $memberid = intval($this->_G['g_memberid']);
        $shakeid = intval($this->_G['g_shakeid']);

        $befData = redis2("get","shakeSendNum-".$memberid);
        $shakeuserdata = redis2("get","shakeUser-".$memberid."-".$shakeid);

        $shakeuserdata = C::t("#api#shake")->dataTurn($shakeuserdata,"get");


        //记录用户预售的总次数
        $userAddAllNum = redis2("get","userAddAllNum-".$memberid);
        if($userAddAllNum){
            $userAddAllNum = intval($userAddAllNum);
        }else{
            $userAddAllNum = 0;
        }

        //获取用户已用预售摇奖次数
        $userUsedAllNum = redis2("get","userUsedAllNum-".$memberid);
        if($userUsedAllNum){
            $userUsedAllNum = intval($userUsedAllNum);
        }else{
            $userUsedAllNum = 0;
        }


        return array("Error"=>0,"Msg"=>"获取缓存次数","befData"=>$befData,"shakeuserdata"=>$shakeuserdata,"ddd"=>1,
            "userAddAllNum"=>$userAddAllNum,
            "userUsedAllNum"=>$userUsedAllNum

        );

    }

    public function queryLog(){
//        $thisData = redis2("zrange","allLogData66",array(-10,-1));
        $thisData = redis2("zrange","allLogData66");
        return array("Error"=>0,"Msg"=>"查询中奖数据成功","data"=>$thisData);
    }

    public function addCache(){
//        $befData = redis2("get","shakeSendNum-2073243");
//        $shakeuserdata = redis2("get","shakeUser-2073243-46");

        $count = intval($this->_G['g_count']);
        $memberid = intval($this->_G['g_memberid']);
        $befData = redis2("set","shakeSendNum-".$memberid,$count);


        return array("Error"=>0,"Msg"=>"增加次数成功");

    }

    public function deleteCache(){


        $memberid = intval($this->_G['g_memberid']);

//        $shakedata = redis2("get","getshake-DJEHBSUAAY");
//        $shakeuserdata = redis2("get","shakeUser-"+$memberid+"-46");
//        $shakelogdata = redis2("get","allLogData66");
//
//        $shakedata = C::t("#api#shake")->dataTurn($shakedata,"get");
//        $shakeuserdata = C::t("#api#shake")->dataTurn($shakeuserdata,"get");
//        $shakelogdata = C::t("#api#shake")->dataTurn($shakelogdata,"get");


//        $shakedata = redis2("rm","getshake-DJEHBSUAAY");
//        $shakelogdata = redis2("rm","allLogData66");
//        $shakeuserdata = redis2("rm","shakeUser-".$memberid."-46");
//        $shakedata = redis2("rm","getshake-DJEHBSUAAY");
        $shakedata = redis2("rm","getshake-DJEHBSUAAY");
//        $shakedata = redis2("rm","currentaddflag-736-53");

        return array("Error"=>0,"Msg"=>"清除数据成功");



    }

    public function shake_detail(){

        if($this->_memberId<=0){
            return array("Error"=>6007,"Msg"=>"会员信息获取错误","opne"=>$this->_openid,"mmeb"=>$this->_memberId,"app"=>$this->_app);
        }
        $id = intval($this->_G['g_id']);
        $thisShake = C::t('#api#shake')->getshake($id);

        if(!$thisShake){
            return array("Error"=>6666,"Msg"=>"敬请期待下次活动","memberId"=>$this->_memberId,"openid"=>$this->_openid,"app"=>$this->_app);
        }

        $shakeUser = C::t("#api#shake")->shakeUser(); //获取会员信息
        if(!$shakeUser || $shakeUser['gid'] == -1 || !$shakeUser['gid']){
            return array("Error"=>6004,"Msg"=>"请先注册成会员","shakeUser"=>$shakeUser);
        }
//        $enterprise = C::t("#api#coupon")->getMemberEnterprise($this->_memberId);
//        if(!$enterprise){
//            return array("Error"=>6009,"Msg"=>"请先选择企业");
//        }
        $thisShake['prizeArr'] = $thisShake['prize']?json_decode($thisShake['prize'],true):"";  //奖品

        $surplusNum = 0; //剩余摇奖次数
        $afterTime = 0; //下一次摇奖时间

        if(TIME < $thisShake['btime']){
            $afterTime = $thisShake['btime'] - TIME;
        }

        $endTime = $thisShake['etime'] - TIME;

        //根据会员等级、家庭会员等级获取固定摇奖次数

        $thisUsrNum  = $this->getShakeNumOfMemberOrFamily(0,$thisShake,$shakeUser);
        //        $thisUsrNum += $shakeUser['shakeSendNum'];//+ 额外增加的次数  =  总抽奖次数
        $thisUsrNum += $shakeUser['pointNum'];//+ 积分换算抽奖次数

        //计算剩余可摇奖次数
        $group_num = json_decode($thisShake['group_num'],true);
        if(intval($group_num[$shakeUser['gid']]) == -1){
            $surplusNum = 999;
        }else if($thisUsrNum){
            $surplusNum = $thisUsrNum - intval($shakeUser['allCount']);
            $surplusNum = $surplusNum > 0 ? $surplusNum : 0;
        }else {
            $surplusNum = 0;
        }


        return array("Error"=>0,"Msg"=>"数据获取成功","data"=>$thisShake,"afterTime"=>$afterTime,"surplusNum"=>$surplusNum,"endTime"=>$endTime,'shakeUser'=>$shakeUser,"enterprise"=>$enterprise);
    }

    /**
     * 总共摇奖数量  分为三类
     * $flag    1.只针对于个人会员
     *          2.只针对于家庭会员
     *          3.针对于个人会员、家庭会员
     * $thisShake ： 摇奖信息
     * $shakeUser ： 当前用户具体信息
     */
    public function getShakeNumOfMemberOrFamily($flag,$thisShake,$shakeUser){
        $group_num = json_decode($thisShake['group_num'],true);
        $thisUsrNum = 0;
        if($flag==0){//个人会员
            $thisUsrNum = intval($group_num[$shakeUser['gid']]);

        }

        if($flag==1){//家庭会员（暂时没有相关业务，有时在实现）

        }

        if($flag==3){//个人会员、家庭会员 (注)2018-03-08活动为针对于个人会员、家庭会员  只有家庭会员为翡翠、钻石的抽2次，其他家庭会员级别、个人会员级别都抽1次，代码里写死，后期最好写成可配的
            if($shakeUser['isfam'] == 1 && ( $shakeUser['gid'] ==396  ||  $shakeUser['gid'] ==395)){ //《是家庭会员》  且  （《翡翠》 活 《钻石》）
                $thisUsrNum = 2;
            }else if($shakeUser['isfam'] == 0){// 不是家庭会员则按照数据库里配置来取
                $thisUsrNum = intval($group_num[$shakeUser['gid']]);
            }else{//非翡翠、砖石家庭会员 固定 1次
                $thisUsrNum = 1;
            }
        }

        //设置用户固定摇奖次数
        if(!$shakeUser[userFixedNum]){
            C::t("#api#shake")->setUserFixedNum($thisUsrNum);
        }
        return $thisUsrNum;
    }

    //摇一摇
    public function shake_start(){

        $id = intval($_GET['id']);

        $nowNum = 0;
        $surplusNum = 0;//剩余抽奖次数
        $lastData = array(); //中奖数据

        if($this->_memberId<=0){
            return C::t('#api#shake')->noGetTip(1);
        }
        $thisShake = C::t('#api#shake')->getshake(); //获取摇一摇活动数据
        if(!$thisShake || $thisShake['Error']){
            return C::t('#api#shake')->noGetTip(2);
        }
        if($id!=$thisShake['id']){
            return array("Error"=>6002,"Msg"=>"活动已经切换，请刷新页面");
        }
        if(TIME<$thisShake['btime']){
            return array("Error"=>6003,"Msg"=>"活动未开始");
        }

        $shakeUser = C::t("#api#shake")->shakeUser(); //获取会员信息
        if(!$shakeUser || $shakeUser['gid'] == -1 || !$shakeUser['gid']){
            return array("Error"=>6004,"Msg"=>"请先注册成会员");
        }
//        $enterprise = C::t("#api#coupon")->getMemberEnterprise($this->_memberId);
//        if(!$enterprise){
//            return array("Error"=>6009,"Msg"=>"请先选择企业");
//        }
        //C::t('D')->WriteLogFile('shake1:$shakeUser：'.json_encode($shakeUser),'shakeUser.log','Debug');

        //根据会员等级、家庭会员等级获取固定摇奖次数
        $thisUsrNum  = $this->getShakeNumOfMemberOrFamily(0,$thisShake,$shakeUser);
        //        $thisUsrNum += $shakeUser['shakeSendNum'];//+ 额外增加的次数  =  总抽奖次数
        $thisUsrNum += $shakeUser['pointNum'];//+ 积分换算抽奖次数


        if(!$thisUsrNum){
            if($thisUsrNum==0){
                return array("Error"=>6006,"Msg"=>"很抱歉，您的机会已经用光了","shakeUser"=>$shakeUser);
            }else{
                return C::t('#api#shake')->noGetTip(4);
            }
        }
//        $surplusNum = $thisUsrNum==-1?-1:$thisUsrNum - intval($shakeUser['allCount']) - 1;
//        $surplusNum = $surplusNum<0 && $thisUsrNum!=-1?0:$surplusNum;//剩余摇奖数量

        $memeberidArr = array(
            //'om0Kyv970kPO3uau8KPsbMrr8bJs'//曹婷
            // ,'om0Kyvy_6C4s6ps_29ATAJK9cfkY'//张春强
//            '1658646',//吴超
//            '2073243'//小妹妹
        );

        if($thisUsrNum!=-1 && intval($shakeUser['allCount'])>=$thisUsrNum && !in_array($this->_memberId,$memeberidArr)){ //您的机会已经用光了
            return array("Error"=>6006,"Msg"=>"很抱歉，您的机会已经用光了","shakeUser"=>$shakeUser);
            //return C::t('#api#shake')->noGetTip(5);
            //return array("Error"=>0,"Msg"=>"很抱歉，您的机会已经用光了");
        }
        $g= redis2("get","shakeTake-".$thisShake['id']."-".$this->_memberId);
        if(!$g){
            redis2("set","shakeTake-".$thisShake['id']."-".$this->_memberId."-".$id,$this->_memberId);
        }
        $queueArr = C::t('#api#shake')->addQueue(); //摇奖排队
        if($queueArr){
            return $queueArr;
        }

        if($thisShake['yesnum']!=-1 && intval($shakeUser['yesgetNUm'])>=$thisShake['yesnum']){ //判断总中奖数是否超过活动设置的中奖数
            return C::t('#api#shake')->noGetTip(-1);
        }

        $prize = $thisShake['prize']?json_decode($thisShake['prize'],true):array();  //奖品

        $typeNum = $thisShake['typenum']?json_decode($thisShake['typenum'],true):array(); //奖品类别摇奖次数

        $thisMaxNumData = C::t("#api#shake")->shakeMaxNum($prize); //中奖最大基数

        //遍历10000次，每次如果抽中的奖品不符合中奖规则，那么自动进行下一次抽奖，直到抽中符合规则的奖品，或者循环到10000次自动跳出，返回为未中奖信息
        $repeatCount = 20;//遍历次数
        $repeatIndex = 0;
        $windataarray = array();
        while(true){
            $repeatIndex = $repeatIndex+1;
            if($repeatIndex>=$repeatCount){//跳出循环
                break;
            }

            $num = mt_rand(1,$thisMaxNumData[0]);   //随机数
            //根据抽奖随机数，获取抽中奖品
            $lastData = $this->getPriceByNum($prize,$thisMaxNumData,$num,$typeNum);
            //判断当前摇奖是否有效
            $winningData = $this->isWinning($lastData,$thisShake,$shakeUser);
            $windataarray[] = $winningData;
            //如果摇奖成功，则记录日志，并且返回前台
            if($winningData && $winningData["Error"]==0){

                //摇奖记录
                $thisTime = microtime(true);
                $thisString = $num ."-" . $thisMaxNumData[0];
                $thisLogData = array($thisTime,$thisString);
                redis2("zadd","shake_rand-".$thisShake['id'],$thisLogData);

                return $winningData;
            }else if($winningData && ($winningData["thisBool"]==13 || $winningData["thisBool"]==-6)){
                return $winningData;
            }
        }

//        $returndata = C::t('#api#shake')->noGetTip(-2);
//        $returndata["windataarray"] = $windataarray;

//        return $returndata;
        //以上去掉循环
//        return C::t('#api#shake')->noGetTip(-2);
        /*
               $num = mt_rand(1,$thisMaxNumData[0]);   //随机数

               $thisTime = microtime(true);
               $thisString = $num ."-" . $thisMaxNumData[0];
               $thisLogData = array($thisTime,$thisString);
               redis2("zadd","shake_rand-".$thisShake['id'],$thisLogData);

               //根据抽奖随机数，获取抽中奖品
               $lastData = getPriceByNum($prize,$thisMaxNumData,$num,$typeNum);
       */

        //C::t('D')->WriteLogFile('shake:$pvs'.json_encode($pvs).",num：".$num.",maxNum：".$maxNum.",LastPo".$LastPow."，pointNum：".$pointNum,'shake_start.log','Debug');

        /*

                if($lastData){  //中奖

                    $shakeInit = C::t("#api#shake")->shakeInit($lastData); //初始化中奖数据
                    if($shakeInit['Error']){
                        return $shakeInit;
                    }

                    $insertBool = C::t("#api#shake")->insertBool(); //判断是否有人在中奖
                    if(is_array($insertBool)){
                        return $insertBool;
                    }

                    $insertArr = array();

                    $insertArr = C::t("#api#shake")->shakePrize();  //获取插入的数据
                    if($insertArr['Error']){
                        return $insertArr;
                    }

                    $numInsertBool = C::t("#api#shake")->numInsertBool();///判断中奖数量和当前用户此奖品类别中奖数
                    if($numInsertBool){
                        return $numInsertBool;
                    }

                    $insertArr['tableid'] = $lastData['tableid'];
                    $insertArr['tablename'] = $lastData['tablename'];
                    $insertArr['tabletype'] = $lastData['tabletype'];
                    $insertArr['thumb'] = $lastData['thumb'];
                    $insertArr['prize_key'] = $lastData['prize_key'];
                    $insertArr['mds'] = $lastData['mds'];
                    $insertArr['yetget'] = 1;

                    C::t('#api#shake')->shakeInsert($insertArr); //将中奖记录插入队列

                    return array("Error"=>0,"Msg"=>$thisShake['reply_get'],"data"=>$insertArr);

                }else{
                    return C::t('#api#shake')->noGetTip(-2);
                }*/

    }

    /**
     * 判断是否中奖
     * @param $lastDat    中奖奖品
     * @param $thisShake  当前摇奖活动数据
     */
    public function isWinning($lastData,$thisShake,$shakeUser){
        if($lastData){  //中奖
            $shakeInit = C::t("#api#shake")->shakeInit($lastData); //初始化中奖数据
            if($shakeInit['Error']){
                return $shakeInit;
            }

            $insertBool = C::t("#api#shake")->insertBool(); //判断是否有人在中奖
            if(is_array($insertBool)){
                return $insertBool;
            }

            $insertArr = array();

            $insertArr = C::t("#api#shake")->shakePrize();  //获取插入的数据
            if($insertArr['Error']){
                return $insertArr;
            }

            $numInsertBool = C::t("#api#shake")->numInsertBool($lastData);///判断中奖数量和当前用户此奖品类别中奖数
            if($numInsertBool){
                return $numInsertBool;
            }

            $insertArr['tableid'] = $lastData['tableid'];
            $insertArr['tablename'] = $lastData['tablename'];
            $insertArr['tabletype'] = $lastData['tabletype'];
            $insertArr['thumb'] = $lastData['thumb'];
            $insertArr['prize_key'] = $lastData['prize_key'];
            $insertArr['mds'] = $lastData['mds'];
            $insertArr['nickname'] = $shakeUser['nickname'];
            $insertArr['phone'] = $shakeUser['number_other'];
            $insertArr['yetget'] = 1;

            C::t('#api#shake')->shakeInsert($insertArr); //将中奖记录插入队列

            return array("Error"=>0,"Msg"=>$thisShake['reply_get'],"data"=>$insertArr);

        }else{
            return C::t('#api#shake')->noGetTip(-2);
        }
    }

    /**
     * 获取当前抽中的奖品
     * @param $prize  奖品信息
     * @param $thisMaxNumData  中奖最大基数
     * @param $num   随机数
     * @param $typeNum  奖品类别摇奖次数
     * @return mixed 当前抽中的奖品
     */
    public function getPriceByNum($prize,$thisMaxNumData,$num,$typeNum){
        $nowNum = 0;
        foreach($prize as $pk => $pv) { //判断随机数在哪个奖品中
            //C::t('D')->WriteLogFile('shake1:$pv：'.json_encode($pv).",time：".TIME,'prize.log','Debug');
            if(($pv['btime'] && $pv['btime']>TIME) || ($pv['etime'] && $pv['etime']<TIME)){
                continue;
            }
            $befNum = $nowNum;
            $nowNum += $pv['percent'] * $thisMaxNumData[1];  //奖品所在区域
            //C::t('D')->WriteLogFile('shake2:nowNum：'.$nowNum.",befNum：".$befNum.",nowNum：".$nowNum,'prize.log','Debug');
            if ($num > $befNum && $num <= $nowNum) {
                $pv = C::t("#api#shake")->getPrizeKey($prize,$pv);//确保百分百中奖
                $thisTime = microtime(true);
                $pv['mds'] = md5($thisTime.$pv['prize_key']);
                $pv['nowNow'] = $num;
                $pv['typeNum'] = intval($typeNum[$pv['tabletype']]);
                $lastData = $pv;
                break;
            }
        }
        return $lastData;
    }
    public function cashPrizeList(){

        DB::SetMainDB(DB_ESHOP);
        $arr = DB::fetch_all("select cash_title,price,is_verify from %t where mid=%s and member_id = %d  ",array("es_cash_winning_prize",$this->_mid,$this->_memberId));
        $count = 0;
        if($arr){
            foreach($arr as $logK => $logV){
                if($logV['is_verify']==0){
                    $count += $logV['price'];
                }
            }
            $count = number_format($count/100,2);
        }else{
            $arr = array();
        }

        return array("Error"=>0,"Msg"=>"数据获取成功","data"=>$arr,"count"=>$count);
    }
    public function newPrizeList(){
        $couponLogArr = C::t("#api#coupon")->couponLogFetch(" `id`,`title`,`coupon_id`,`inputtime`,format((`price`/100),2) as price,`status`,`description`,`limit_btime`,`limit_etime`,`is_verify`,`description`,`type`",DB::format("  and inputtime>=1550073600 and gettype=4 and member_id=%d order by status asc", array($this->_memberId)));

        if($couponLogArr){
            foreach($couponLogArr as $logK => $logV){

                $couponLogArr[$logK]['coupon_log_id'] = $logV['id'];

                $couponLogArr[$logK]['do_limit_btime'] = date("Y.m.d H:i:s",$logV['limit_btime']);
                $couponLogArr[$logK]['do_limit_etime'] = date("Y.m.d H:i:s",$logV['limit_etime']);
                $couponLogArr[$logK]['inputtime'] = date("Y.m.d H:i:s",$logV['inputtime']);
                $couponLogArr[$logK]['price'] = floor($couponLogArr[$logK]['price']);
                $couponLogArr[$logK]['ewm'] = "/app/member/coupon_verify_line?id=".$couponLogArr[$logK]['coupon_log_id']."&sign=".$this->_memberId;

                $couponLogArr[$logK]['used'] = TIME > $logV['limit_etime'] ? 1 : 0; //是否过期
//                if($logV['coupon_id']==4737||$logV['coupon_id']==4751){
//                    DB::SetMainDB(DB_ESHOP);
//                    $couponLogArr[$logK]['couponLogId'] =DB::result_first("select couponLogId from %t where status=1 and coupon_log_id=%d", array("hipay_send_coupon_log", $logV['id']));
//                }else{
//                    $couponLogArr[$logK]['couponLogId'] ='';
//                }
            }
        }else{
            $couponLogArr = array();
        }

        return array("Error"=>0,"Msg"=>"数据获取成功","data"=>$couponLogArr);
    }
    public function getVerifyCount(){
//        $log_ids = $this->_G['g_ids'];
//        $data = explode(",", $log_ids);
        $arrry=array();
        $allCount=0;
        $data = $this->_G['g_ids'];
        foreach ($data as $k=>$v) {
            $arrry[] = $v['id'];
        }
        DB::SetMainDB(DB_ESHOP);
        $arr = DB::fetch_all("select COUNT(id) as count,`title` from %t where mid=%s and status=1 and is_verify=0 and id in (%n) group by title ",array("es_coupon_log",$this->_mid,$arrry));
        foreach($arr as $logK => $logV) {
            $allCount += $logV['count'];
        }

//        foreach ($data as $k=>$v){
//            DB::SetMainDB(DB_ESHOP);
//            $coupon_id = DB::result_first("select COUNT(id) as count,`title` from %t where mid=%s and status=1 and is_verify=0 and id in %n group by title ",array("es_coupon_log",$this->_mid,$data));
//            $coupon[]= $coupon_id;
//        }
//        $verfyCount=array_count_values($coupon);
//        foreach($verfyCount as $logK => $logV) {
//            $array['coupon_id']=$logK;
//            DB::SetMainDB(DB_ESHOP);
//            $couponInfo= DB::fetch_first("select title from %t where mid=%s and id=%d ",array("es_coupon",$this->_mid,$logK));
//            $array['title']=$couponInfo['title'];
//            $array['count']=$logV;
//            $arr[]=$array;
//        }

        return array("Error"=>0,"Msg"=>"数据获取成功","allCount"=>$allCount,"data"=>$arr);
    }
    public function getMemberEnterprise(){

        $enterprise = C::t("#api#coupon")->getMemberEnterprise($this->_memberId);
        if($enterprise){
            return array("Error"=>0,"Msg"=>"数据获取成功","data"=>$enterprise);
        }else{
            return array("Error"=>404,"Msg"=>"未选择企业","data"=>$enterprise);
        }

    }
    public function enterpriseList(){

        $enterpriseList = C::t("#api#coupon")->enterpriseFetch();
        return array("Error"=>0,"Msg"=>"数据获取成功","data"=>$enterpriseList);
    }
    public function getPoint(){

        $enterpriseList = C::t("#api#shake")->getMemberPoint();
        return array("Error"=>0,"Msg"=>"数据获取成功","data"=>$enterpriseList);
    }
    public function setEnterprise(){

        $id = intval($_GET['id']);
        $name = $_GET['name'];
        $enterprise = C::t("#api#coupon")->getMemberEnterprise($this->_memberId);
        if($enterprise){
            return array("Error"=>0,"Msg"=>"保存成功");
        }else{
            $result = C::t("#api#coupon")->setMemberEnterprise($this->_memberId,$id,$name);
            if($result){
                return array("Error"=>0,"Msg"=>"保存成功");
            }
        }
    }
    //中奖列表
    public function prizeList(){

        if($this->_memberId<=0){
            return array("Error"=>6007,"Msg"=>"会员信息获取错误");
        }

        return $this->newPrizeList();//优惠券
        return $this->cashPrizeList();//现金券

        /*$thisKey = "owmPrizeList-".$this->_openid;
        $thisData = redis2("get",$thisKey);
        $thisObj = C::t("#api#shake")->dataTurn($thisData,"get");

        if($thisObj){

            $couponIds = array();
            $couponLogIds = array();

            foreach($thisObj as $coupon){
                if(!in_array($coupon['tableid'],$couponIds)){
                    $couponIds[] = $coupon['tableid'];
                }
                if($coupon['coupon_log_id']){
                    $couponLogIds[] = $coupon['coupon_log_id'];
                }
            }

            $couponLogArr = C::t("#api#coupon")->couponLogFetch(" `id`,`coupon_id`,`is_verify`",DB::format(" and member_id=%d and coupon_id in(%n)", array($this->_memberId,$couponIds)));

            foreach($thisObj as $key => $arr){

                $updateBool = false;

                if($couponLogArr){  //更新优惠券记录数据
                    foreach($couponLogArr as $logKey => $couponLog){
                        if(in_array($couponLog['id'], $couponLogIds)){
                            if($couponLog['id'] == $arr['coupon_log_id']){
                                $updateBool = true;
                                $thisObj[$key]['is_verify'] = $couponLog['is_verify'];
                                unset($couponLogArr[$logKey]);
                            }
                        }else{
                            if(!$arr['coupon_log_id'] && $couponLog['coupon_id'] == $arr['tableid']){
                                $updateBool = true;
                                $thisObj[$key]['is_verify'] = $couponLog['is_verify'];
                                $thisObj[$key]['coupon_log_id'] = $couponLog['id'];
                                unset($couponLogArr[$logKey]);
                            }
                        }
                    }
                }

                if(!$updateBool){
                    $thisObj[$key]['is_verify'] = 0;
                    $thisObj[$key]['coupon_log_id'] = 0;
                }

                $thisObj[$key]['do_limit_btime'] = date("Y.m.d",$arr['limit_btime']);
                $thisObj[$key]['do_limit_etime'] = date("Y.m.d",$arr['limit_etime']);

                $thisObj[$key]['ewm'] = "/app/member/coupon_verify_line?id=".$thisObj[$key]['coupon_log_id']."&sign=".$this->_memberId;

                $thisObj[$key]['used'] = TIME > $arr['limit_etime'] ? 1 : 0; //是否过期
            }

            $thisData = C::t("#api#shake")->dataTurn($thisObj);
            redis2("set",$thisKey,$thisData);

        }else{
            $thisObj = array();
        }

        return array("Error"=>0,"Msg"=>"数据获取成功","data"=>$thisObj);*/
    }

    //修改门店
    public function outletUpdate(){
        $outletId = intval($this->_G['g_outlet_id']);
        $couponLogId = intval($this->_G['g_coupon_log_id']);

        $couponLog = C::t("#api#coupon")->couponLogFetch(" `coupon_id`,`limit_etime`,`is_verify`",DB::format(" and member_id=%d and id=%d", array($this->_memberId,$couponLogId)),"first");
        if(!$couponLog){
            return array("Error"=>6702,"Msg"=>"卡券信息错误");
        }
        if($couponLog['is_verify']){
            return array("Error"=>6701,"Msg"=>"该卡券已经核销过了");
        }

        $couponEnterprise =  C::t("#api#coupon")->couponEnterpriseFetch(" enterprise_id as id,enterprise_title as title",DB::format(" and coupon_id=%d", array($couponLog['coupon_id'])));

        if(TIME > $couponLog['limit_etime']){
            $error = $couponEnterprise ? 6801 : 6802;
            return array("Error"=>$error,"Msg"=>"卡券已过期");
        }

        $couponOutlet =  C::t("#api#coupon")->couponOutletFetch(" outlet_id",DB::format(" and member_id=%d and coupon_log_id=%d", array($this->_memberId,$couponLogId)),"first");

        if($outletId){
            $outletTitle = $this->outletSelectTitle($outletId,$couponEnterprise);
            if(!$outletTitle){
                return array("Error"=>6703,"Msg"=>"门店不存在");
            }
            if($couponOutlet){
                return array("Error"=>6704,"Msg"=>"该卡券已经绑定【".$outletTitle."】门店了");
            }

            $insertArr = array();
            $insertArr['outlet_id'] = $outletId;
            $insertArr['coupon_log_id'] = $couponLogId;
            C::t("#api#coupon")->couponOutletInsert($insertArr);

            return array("Error"=>0,"Msg"=>"门店绑定成功");

        }

        $returnArr = array();
        if($couponEnterprise){
            $returnArr['outlet_id'] = $couponOutlet ? $couponOutlet['outlet_id'] : 0;
            $returnArr['outlet_title'] = $couponOutlet ? $this->outletSelectTitle($couponOutlet['outlet_id'],$couponEnterprise) : "";
        }else{
            $couponEnterprise = array();
        }

        return array("Error"=>0,"Msg"=>"数据获取成功","data"=>$returnArr,"outletArr"=>$couponEnterprise);
    }

    public function outletSelectTitle($outletId,$outletArr){
        $title = "";
        foreach($outletArr as $thisV){
            if($thisV['id'] == $outletId){
                $title = $thisV['title'];
            }
        }

        return $title;
    }

    //加载实物表单
    public function getForm(){
        $id = intval($this->_G['g_id']);
        $tablename = trim(strip_tags($this->_G['g_tablename']));

        $return = C::t("#api#shake")->getForm($tablename,$id);

        return $return;
    }

    //添加信息
    public function actForm(){
        $mds = trim(strip_tags($this->_G['g_mds']));
        $info = $this->_G['g_info'];

        C::t("#api#shake")->addForm($mds,$info);

        return array("Error"=>0,"Msg"=>"信息录入成功");
    }

    //重新获取微信用户信息
    public function getSharkUser(){
        $shakeid = intval($this->_G['g_id']);
        $shakeUser = C::t("#api#shake")->shakeUser($shakeid);
        $thisShake = C::t('#api#shake')->getshake();

        //根据会员等级、家庭会员等级获取固定摇奖次数
        $thisUsrNum  = $this->getShakeNumOfMemberOrFamily(0,$thisShake,$shakeUser);
//        $thisUsrNum += $shakeUser['shakeSendNum'];//+ 额外增加的次数  =  总抽奖次数
        $thisUsrNum += $shakeUser['pointNum'];//+ 积分换算抽奖次数

        //计算剩余可摇奖次数
        $group_num = json_decode($thisShake['group_num'],true);
        if(intval($group_num[$shakeUser['gid']]) == -1){
            $surplusNum = 999;
        }else if($thisUsrNum){
            $surplusNum = $thisUsrNum - intval($shakeUser['allCount']);
            $surplusNum = $surplusNum > 0 ? $surplusNum : 0;
        }else {
            $surplusNum = 0;
        }
        $g=1;
//        $enterprise = C::t("#api#coupon")->getMemberEnterprise($this->_memberId);
//        $id=json_decode($thisShake['id'],true);
//        $g= redis2("get","shakePointTake-".$this->_memberId."-".$id);
//        if(!$g){
//            $g=0;
//            redis2("set","shakePointTake-".$this->_memberId."-".$id,0);
//        }
        return array("Error"=>0,"Msg"=>"数据获取成功","data"=>$shakeUser,"shake_num"=>$surplusNum,"take"=>$g);
    }
    public function takeActivity(){
        $thisShake = C::t('#api#shake')->getshake();
        $id=json_decode($thisShake['id'],true);
        $g=redis2("set","shakePointTake-".$this->_memberId."-".$id,1);
        return array("Error"=>0,"Msg"=>"领取成功","data"=>$g);
    }
    public function sendCoupon(){
        $thisCoupon = C::t('#api#shake')->getshakeSendCoupon();
        $thisCoupon['mid'] = $this->_mid;
        $thisCoupon['member_id'] = $this->_memberId;
        $logId = C::t('#api#shake')->sendCoupon($thisCoupon);
        $thisShake = C::t('#api#shake')->getshake();
        $id=json_decode($thisShake['id'],true);
        $g=redis2("set","shakeCouponTake-".$this->_memberId."-".$id,$logId);
        return array("Error"=>0,"Msg"=>"领取成功","data"=>$g);
    }
//    //清楚中奖基数
//    public function rmMaxNum(){
//        $shakeid = intval($this->_G['g_id']);
//        redis2("rm","shakeMaxNum-".$shakeid);
//    }
//
//    public function rmShakeUser(){
//        $shakeid = intval($this->_G['g_id']);
//        redis2("rm","shakeUser-".$this->_openid."-".$shakeid);
//    }
//
//    public function getInsertBool(){
//        $shakeid = intval($this->_G['g_id']);
//        $key = trim($this->_G['g_key']);
//        $thisBool = redis2("get","shakeInsertBool-".$shakeid."-".$key);
//        return array("Error"=>0,"Msg"=>"数据获取成功","data"=>$thisBool);
//    }
    public function getShakeId(){
        $id = intval($this->_G['g_id']);
        $thisShake = C::t('#api#shake')->getshake($id);
        return array("Error"=>0,"Msg"=>"数据获取成功","data"=>$thisShake);
    }
    public function allLogData(){
        $id = trim($this->_G['g_id']);
        $thisData = redis2("zrange","allLogData-".$id,array(0,-1));
        if($thisData){
            foreach($thisData as $thisKey => $thisArr){
                $thisData[$thisKey] = C::t("#api#shake")->dataTurn($thisArr,"get");

            }
            $coupon1= array(5552,5553,5554,5555,5556,5557,5558,5559,5560,5567);//一等奖
            $coupon2= array(5561,5568);
            $coupon3= array(5562,5569);
            $coupon4= array(5564,5570);
            $coupon5= array(5565);
            $coupon6= array(5566);
            $coupon7= array(5571);
            foreach ($thisData as $k=>$v){
                $data[$k]['phone']=$v['phone'];
                $data[$k]['shake_id']=$v['shake_id'];
                $data[$k]['title']=$v['title'];
                $data[$k]['tableid']=$v['tableid'];
                if(in_array($v['tableid'], $coupon1)){
                    $data[$k]['prize']=1;
                }elseif(in_array($v['tableid'], $coupon2)){
                    $data[$k]['prize']='二等奖中奖用户';
                }elseif(in_array($v['tableid'], $coupon3)){
                    $data[$k]['prize']='三等奖中奖用户';
                }elseif(in_array($v['tableid'], $coupon4)){
                    $data[$k]['prize']='四等奖中奖用户';
                }elseif(in_array($v['tableid'], $coupon5)){
                    $data[$k]['prize']='五等奖中奖用户';
                }elseif(in_array($v['tableid'], $coupon6)){
                    $data[$k]['prize']='六等奖中奖用户';
                }elseif(in_array($v['tableid'], $coupon7)){
                    $data[$k]['prize']='七等奖中奖用户';
                }
            }
        }
        return array("Error"=>0,"Msg"=>"数据获取成功","data"=>$data);
    }
    public function sendPrize(){//手动发奖
        $shake = new shake_insertlog();
        $shake->insert();
        return array("Error"=>0,"Msg"=>"数据获取成功","data"=>123);
    }
    public function getTime(){
        $time = TIME;
        $userInfo = $this->getWxUserInfo();
        return array("Error"=>0,"time"=>$time,"subscribe"=>$userInfo['subscribe']);
    }
    public function getWxUserInfo(){
        $appId = $this->_wxConf['appId'];
        $secret = $this->_wxConf['secret'];
        $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appId."&secret=".$secret;
        $data = DoCurl($url);
        $data = json_decode($data, true);
        $userUrl="https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$data['access_token']."&openid=".$this->_openid."&lang=zh_CN";
        $userInfo = DoCurl($userUrl);
        $userInfo = json_decode($userInfo, true);
        return  $userInfo;
    }
    //临时发奖
    public function sendCouponTem(){
        $thisData = redis2("zrange","allLogData-160",array(0,-1));
        if($thisData) {
            foreach ($thisData as $thisKey => $thisArr) {
                $thisData[$thisKey] = C::t("#api#shake")->dataTurn($thisArr, "get");

            }
            foreach ($thisData as $k=>$v){
                $couponLogArr = array();
                $couponLogArr['inputtime'] = time();
                $couponLogArr['mid'] = $v['mid'];

                $couponLogArr['coupon_id'] = $v['tableid'];
                $couponLogArr['openid'] = $v['openid'];
                $couponLogArr['member_id'] = $v['member_id'];
                $couponLogArr['gettype'] = 4;
                $couponLogArr['title'] = $v['title'];

                $couponLogArr['store_id'] = $v['store_id'];
                $couponLogArr['description'] = '';
                $couponLogArr['thumb'] = $v['thumb'];
                $couponLogArr['price'] = $v['price'];
                $couponLogArr['limit_price'] = $v['limit_price'];
                $couponLogArr['limit_user'] = '';
                $couponLogArr['btime'] = $v['btime'];
                $couponLogArr['etime'] = $v['etime'];
                $couponLogArr['limit_btime'] = $v['limit_btime'];
                $couponLogArr['limit_etime'] = $v['limit_etime'];
                $couponLogArr['no_discount_group'] = '';
                $couponLogArr['group_id'] = '';
                $couponLogArr['type'] = 2;
                $couponLogArr['tagstr'] = '';
                $couponLogArr['is_activity'] = 0;

                DB::SetMainDB(DB_ESHOP);
                $thisId = DB::insert("es_coupon_log", $couponLogArr,true);
            }
        }
    }

    public function shake_screen(){

        $nowArr = array();
        $thisData = redis2("zrange","shake_screen",array(-20,-1));
        if($thisData){
            foreach($thisData as $thisKey => $thisArr){
                $nowArr[] = C::t("#api#shake")->dataTurn($thisArr,"get");
            }
        }
        return array("Error"=>0,"Msg"=>"数据获取成功","data"=>$nowArr);
    }
    //读取日志
    public function EchoLogFile()
    {
        $txt = trim($this->_G['g_txt']);
        C::t("D")->EchoLogFile($txt . ".log");
    }

    public function rmCouponRedis(){
        $couponArr = C::t("#api#coupon")->couponFetch(" id"," and `status`=1 and is_activity=1");
        if($couponArr){
            foreach($couponArr as $coupon){
                redis2("rm","getshakeCoupon-".$coupon['id']);
            }
        }

        return array("Error"=>0,"Msg"=>"数据缓存清除成功");
    }

    //获取当前用户中奖信息
//    public function getYetLog(){
//        
//        $openid = trim(strip_tags($this->_G['g_getopenid']));
//        $shakeid = intval($this->_G['g_shakeid']);
//        
//        $yetLog = C::t("#api#shake")->yetLog($openid,$shakeId);
//        
//        return array("Error"=>0,"Msg"=>"信息获取成功","data"=>$yetLog);
//    }
//    
//    
//    //获取用户在活动中的记录
//    public function getThis(){
//        $openid = trim(strip_tags($this->_G['g_getopenid']));
//        $shakeid = intval($this->_G['g_shakeid']);
//        $shakeUser = C::t("#api#shake")->getThisUser($shakeid,$openid);
//        return array("Error"=>0,"Msg"=>"很抱歉，您未中奖","data"=>$shakeUser);
//    }
//    
//    //删除用户在活动中的记录
//    public function rmThis(){
//        $openid = trim(strip_tags($this->_G['g_getopenid']));
//        $shakeid = intval($this->_G['g_shakeid']);
//        $shakeUser = C::t("#api#shake")->rmThisUser($shakeid,$openid);
//    }
//    
//    //删除用户在活动中的记录
//    public function getThisShake(){
//        $shake = C::t("#api#shake")->getshake(1);
//        return array("Error"=>0,"Msg"=>"很抱歉，您未中奖","data"=>$shake);
//    }
//    
//    ///增加活动中奖品的中奖队列
//    public function setShakeInsertBool(){
//        $shakeid = intval($this->_G['g_shakeid']);
//        $num = intval($this->_G['g_num']);
//        for($i=0;$i<$num;$i++){
//            $thisBool = C::t("#api#shake")->dataTurn(1);
//            redis2("set","shakeInsertBool-".$shakeid."-".$i,$thisBool);
//        }
//    }
//    
//    //删除活动中奖品的中奖队列
//    public function rmShakeInsertBool(){
//        $shakeid = intval($this->_G['g_shakeid']);
//        $num = intval($this->_G['g_num']);
//        for($i=0;$i<$num;$i++){
//            redis2("rm","shakeInsertBool-".$shakeid."-".$i);
//        }
//    }

}